package com.yoda.youdianda.common;

import com.yoda.youdianda.domain.SysUser;
import com.yoda.youdianda.domain.YddUser;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 线程变量副本数据
 *
 * @author shawn
 * @date 2022年 11月 12日 23:05
 */

public class ThreadContext {
    private static final ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<>();

    public Object getObject(String key) {
        return threadLocal.get().get(key);
    }

    public static void setObject(String key, Object value) {
        Map<String, Object> map = new HashMap<>();
        map.put(key, value);
        threadLocal.set(map);
    }

    public static String getId(String key) {
        if(Objects.isNull(threadLocal.get())){
            return null;
        }

        if (RC.SYS_ID.equals(key)) {
            Object o = threadLocal.get().get(RC.SYS_USER);
            if (Objects.isNull(o)){
                return null;
            }
            SysUser user = (SysUser) threadLocal.get().get(RC.SYS_USER);
            return user.getId();
        }
        if (RC.YDD_ID.equals(key)) {
            Object o = threadLocal.get().get(RC.YDD_USER);
            if (Objects.isNull(o)){
                return null;
            }
            YddUser user = (YddUser) threadLocal.get().get(RC.YDD_USER);
            return user.getId().toString();
        }
        return null;
    }

    public static void clear() {
        threadLocal.remove();
    }
}

